#include "baidu_cloud.h"
#include "http.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cjson/cJSON.h>

#define TOKEN_URL "https://aip.baidubce.com/oauth/2.0/token"
#define ASR_URL "https://vop.baidu.com/server_api"

/**
 * 获取百度云的访问令牌
 * @param api_key 百度云API Key
 * @param secret_key 百度云Secret Key
 * @return 成功返回令牌字符串，失败返回NULL
 */
char *baidu_get_access_token(const char *api_key, const char *secret_key)
{
    // 构建URL用于获取访问令牌
    char url[1024];
    snprintf(url, sizeof(url), "%s?grant_type=client_credentials&client_id=%s&client_secret=%s", TOKEN_URL, api_key, secret_key);

    // 发送HTTP GET请求
    char *response = http_get(url);
    if (!response)
    {
        fprintf(stderr, "Failed to get response for token request\n");
        return NULL;
    }

    // 解析JSON响应以获取访问令牌
    cJSON *json = cJSON_Parse(response);
    if (!json)
    {
        fprintf(stderr, "Failed to parse JSON from token response\n");
        free(response);
        return NULL;
    }

    cJSON *token = cJSON_GetObjectItem(json, "access_token");
    if (!token || !cJSON_IsString(token))
    {
        fprintf(stderr, "Access token not found in response\n");
        cJSON_Delete(json);
        free(response);
        return NULL;
    }

    // 复制令牌字符串
    char *access_token = strdup(token->valuestring);
    cJSON_Delete(json);
    free(response);
    return access_token;
}

/**
 * 从语音识别响应中提取识别结果
 * @param response 服务器返回的JSON响应
 * @return 成功返回识别的文本，失败返回NULL
 */
char *extract_result(const char *response)
{
    cJSON *json = cJSON_Parse(response);
    if (!json)
    {
        fprintf(stderr, "解析JSON失败\n");
        return NULL;
    }

    cJSON *result = cJSON_GetObjectItemCaseSensitive(json, "result");
    if (!cJSON_IsArray(result) || cJSON_GetArraySize(result) == 0)
    {
        cJSON_Delete(json);
        fprintf(stderr, "结果数组不存在或为空\n");
        return NULL;
    }

    cJSON *first_result = cJSON_GetArrayItem(result, 0);
    if (!cJSON_IsString(first_result))
    {
        cJSON_Delete(json);
        fprintf(stderr, "结果格式错误\n");
        return NULL;
    }

    char *recognition_result = strdup(first_result->valuestring);
    cJSON_Delete(json);
    return recognition_result;
}

/**
 * 使用百度云语音识别服务
 * @param filename 包含录音数据的文件名
 * @param token 访问令牌
 * @param response_code 用于存储HTTP响应代码的变量的地址
 * @return 成功返回识别结果，失败返回NULL
 */
char *baidu_recognize_speech(const char *filename, const char *token, long *response_code)
{
    FILE *file = fopen(filename, "rb");
    if (!file)
    {
        perror("Failed to open file for reading");
        return NULL;
    }

    fseek(file, 0, SEEK_END);
    size_t size = ftell(file);
    rewind(file);

    char *data = malloc(size);
    if (!data)
    {
        fclose(file);
        fprintf(stderr, "Failed to allocate memory for audio data\n");
        return NULL;
    }

    fread(data, 1, size, file);
    fclose(file);

    char url[1024];
    snprintf(url, sizeof(url), "%s?token=%s&cuid=7smartspeaker", ASR_URL, token);

    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Content-Type: audio/pcm; rate=16000");

    char *response = http_post(url, data, size, response_code, headers);
    free(data);
    return response;
}
